package leetcode.editor.cn;

import java.util.HashMap;
import java.util.Map;

public class _337_HouseRobberIii {
    public static void main(String[] args) {
        Solution solution = new _337_HouseRobberIii().new Solution();
    }

    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }
    //leetcode submit region begin(Prohibit modification and deletion)


    class Solution {
        Map<TreeNode, Integer> memo = new HashMap<>();

        public int rob(TreeNode root) {
            if (root == null) {
                return 0;
            }
            if (memo.containsKey(root)) {
                return memo.get(root);
            }
            int res = root.val;
            if (root.left != null) {
                res += rob(root.left.left) + rob(root.left.right);
            }
            if (root.right != null) {
                res += rob(root.right.left) + rob(root.right.right);
            }
            memo.put(root, Math.max(res, rob(root.left) + rob(root.right)));
            return memo.get(root);
        }
    }
//leetcode submit region end(Prohibit modification and deletion)

}